package org.jeecg.modules.yusuannz.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.hqbaoxiao.entity.HqBaoxiao;
import org.jeecg.modules.hqbaoxiao.service.IHqBaoxiaoService;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.model.TreeSelectModel;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.yusuan.entity.NianDuHuiZong;
import org.jeecg.modules.yusuannz.entity.CaiwuZhijieNz;
import org.jeecg.modules.yusuannz.entity.CaiwuZhijieNz;
import org.jeecg.modules.yusuannz.entity.NianDuHuiZongNz;
import org.jeecg.modules.yusuannz.service.ICaiwuZhijieNzService;
import org.jeecg.modules.yusuannz.service.ICaiwuZhijieNzService;
import org.jeecg.modules.zhibiao.entity.CaiwuZhibiao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
* @Description: caiwu_zhijie
* @Author: jeecg-boot
* @Date:   2020-06-15
* @Version: V1.0
*/
@Api(tags="caiwu_zhijienz")
@RestController
@RequestMapping("/yusuan/zhijienz")
@Slf4j
public class CaiwuZhijieNzController extends JeecgController<CaiwuZhijieNz, ICaiwuZhijieNzService> {
   @Autowired
   private ICaiwuZhijieNzService caiwuZhijieService;
   @Autowired
   private ISysDepartService sysDepartService;
   @Autowired
   private IHqBaoxiaoService hqBaoxiaoService;

   /**
    * 分页列表查询
    *
    * @param caiwuZhijie
    * @param pageNo
    * @param pageSize
    * @param req
    * @return
    */
   @AutoLog(value = "caiwu_zhijie-分页列表查询")
   @ApiOperation(value="caiwu_zhijie-分页列表查询", notes="caiwu_zhijie-分页列表查询")
   @GetMapping(value = "/list")
   public Result<?> queryPageList(CaiwuZhijieNz caiwuZhijie,
                                  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                  @RequestParam(name="deptId",required = false) String deptId,
                                  HttpServletRequest req) {
       pageNo = 1;
       pageSize = 1000;
       QueryWrapper<CaiwuZhijieNz> queryWrapper = new QueryWrapper<>(); // QueryGenerator.initQueryWrapper(caiwuZhijie, req.getParameterMap());
       if(StringUtils.isBlank(deptId)) {
           LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
           deptId = user.getOrgCode();
       }
       queryWrapper.eq("dept_id",deptId);
       Page<CaiwuZhijieNz> page = new Page<CaiwuZhijieNz>(pageNo, pageSize);
       IPage<CaiwuZhijieNz> pageList = caiwuZhijieService.page(page, queryWrapper);
       return Result.ok(pageList);
   }

   /**
    *   添加
    *
    * @return
    */
   @AutoLog(value = "caiwu_zhijie-添加")
   @ApiOperation(value="caiwu_zhijie-添加", notes="caiwu_zhijie-添加")
   @PostMapping(value = "/add")
   public Result<?> add(@RequestBody Map param) {
       LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
       String deptId = user.getOrgCode();
       List<Map> list = (List<Map>)param.get("list");
       if(!CollectionUtils.isEmpty(list)){
           List<CaiwuZhijieNz> yusuanList = new ArrayList<>();
           for(Map map:list){
               try {
                   map.remove("key");
                   map.remove("deptId_dictText");
                   ObjectMapper mapper = new ObjectMapper();
                   String jsonInString = mapper.writeValueAsString(map);
                   mapper = new ObjectMapper();
                   CaiwuZhijieNz yusuan = mapper.readValue(jsonInString, CaiwuZhijieNz.class);
                   yusuan.setDeptId(deptId);
                   Integer status = yusuan.getStatus();
                   if(null == status || status<1) {
                       yusuan.setStatus(-1);
                       yusuanList.add(yusuan);
                   }
               }catch (Exception ex){
                   ex.printStackTrace();
               }
           }
           caiwuZhijieService.saveYuSuanData(yusuanList);
       }

       return Result.ok("操作成功！");
   }

   @PostMapping("/addlist")
   public Result<?> addList(@RequestBody List<CaiwuZhijieNz> zhijieList){
       String orgCode = ((LoginUser) SecurityUtils.getSubject().getPrincipal()).getOrgCode();
       String deptId = this.sysDepartService.getOne(new LambdaQueryWrapper<SysDepart>().eq(SysDepart::getOrgCode,orgCode)).getId();
       if(org.apache.commons.collections.CollectionUtils.isNotEmpty(zhijieList)){
           zhijieList.forEach(zhijie->{
               if(StringUtils.isBlank(zhijie.getDeptId()))
                   zhijie.setDeptId(deptId);
           });
       }
       this.caiwuZhijieService.saveOrUpdateBatch(zhijieList);
       return Result.ok("操作成功");
   }

   /**
    *  编辑
    *
    * @param caiwuZhijie
    * @return
    */
   @AutoLog(value = "caiwu_zhijie-编辑")
   @ApiOperation(value="caiwu_zhijie-编辑", notes="caiwu_zhijie-编辑")
   @PutMapping(value = "/edit")
   public Result<?> edit(@RequestBody CaiwuZhijieNz caiwuZhijie) {
       caiwuZhijieService.updateById(caiwuZhijie);
       return Result.ok("编辑成功!");
   }

   /**
    *   通过id删除
    *
    * @param id
    * @return
    */
   @AutoLog(value = "caiwu_zhijie-通过id删除")
   @ApiOperation(value="caiwu_zhijie-通过id删除", notes="caiwu_zhijie-通过id删除")
   @DeleteMapping(value = "/delete")
   public Result<?> delete(@RequestParam(name="id",required=true) String id) {
       caiwuZhijieService.removeById(id);
       return Result.ok("删除成功!");
   }

   /**
    *  批量删除
    *
    * @param ids
    * @return
    */
   @AutoLog(value = "caiwu_zhijie-批量删除")
   @ApiOperation(value="caiwu_zhijie-批量删除", notes="caiwu_zhijie-批量删除")
   @DeleteMapping(value = "/deleteBatch")
   public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
       this.caiwuZhijieService.removeByIds(Arrays.asList(ids.split(",")));
       return Result.ok("批量删除成功!");
   }

   /**
    * 通过id查询
    *
    * @param id
    * @return
    */
   @AutoLog(value = "caiwu_zhijie-通过id查询")
   @ApiOperation(value="caiwu_zhijie-通过id查询", notes="caiwu_zhijie-通过id查询")
   @GetMapping(value = "/queryById")
   public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
       CaiwuZhijieNz caiwuZhijie = caiwuZhijieService.getById(id);
       if(caiwuZhijie==null) {
           return Result.error("未找到对应数据");
       }
       return Result.ok(caiwuZhijie);
   }

   /**
   * 导出excel
   *
   * @param request
   * @param caiwuZhijie
   */
   @RequestMapping(value = "/exportXls")
   public ModelAndView exportXls(HttpServletRequest request, CaiwuZhijieNz caiwuZhijie) {
       return super.exportXls(request, caiwuZhijie, CaiwuZhijieNz.class, "caiwu_zhijie");
   }

   /**
     * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
   @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
   public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
       return super.importExcel(request, response, CaiwuZhijieNz.class);
   }

   @GetMapping("/nianduhuizong")
   public Result<?> nianduhuizong(@RequestParam(name="orgCode",required = false) String orgCode){
       if(StringUtils.isBlank(orgCode)){
           orgCode = ((LoginUser) SecurityUtils.getSubject().getPrincipal()).getOrgCode();
       }
       List<NianDuHuiZongNz> list = this.caiwuZhijieService.nianduhuizong(orgCode);
       return Result.ok(list);
   }

    /**
     * 加载一级节点/如果是同步 则所有数据
     */
    @RequestMapping(value = "/loadData", method = RequestMethod.GET)
    public Result<List<CaiwuZhijieNz>> loadTreeRoot(@RequestParam( value = "deptId",required = false)String deptId,@RequestParam(name="pid") String pid) {
        if(StringUtils.isBlank(deptId)){
            String orgCode = ((LoginUser) SecurityUtils.getSubject().getPrincipal()).getOrgCode();
            deptId = this.sysDepartService.getOne(new LambdaQueryWrapper<SysDepart>().eq(SysDepart::getOrgCode,orgCode)).getId();
        }
        Result<List<CaiwuZhijieNz>> result = new Result<List<CaiwuZhijieNz>>();
        try {
            List<CaiwuZhijieNz> ls = this.caiwuZhijieService.listData(deptId,pid);
            loadDataChildren(deptId,ls);
            result.setResult(ls);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage(e.getMessage());
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * 递归求子节点 同步加载用到
     */
    private void loadDataChildren(String deptId,List<CaiwuZhijieNz> ls) {
        for (CaiwuZhijieNz tsm : ls) {
            List<CaiwuZhijieNz> temp = this.caiwuZhijieService.listData(deptId,tsm.getTreeId());
            if(temp!=null && temp.size()>0) {
                tsm.setChildren(temp);
                loadDataChildren(deptId,temp);
            }
        }
    }

    @GetMapping("/getbycateanddept")
    public Result<?> getByCateAndDept(@RequestParam String categoryId){
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String orgCode = user.getOrgCode();

        String deptId = this.sysDepartService.getOne(new LambdaQueryWrapper<SysDepart>().eq(SysDepart::getOrgCode,orgCode), false).getId();
        CaiwuZhijieNz zhijie = this.caiwuZhijieService.getOne(new LambdaQueryWrapper<CaiwuZhijieNz>().eq(CaiwuZhijieNz::getDeptId,deptId).eq(CaiwuZhijieNz::getCategoryId,categoryId));
        String hjshenheshu = null == zhijie?"0":zhijie.getHjshenheshu();
        Double amount = Double.parseDouble(hjshenheshu);

        List<HqBaoxiao> list = this.hqBaoxiaoService.list(new LambdaQueryWrapper<HqBaoxiao>().eq(HqBaoxiao::getBaoxStatus,1).eq(HqBaoxiao::getSysOrgCode,orgCode));
        if(!CollectionUtils.isEmpty(list)){
            for(HqBaoxiao item:list){
                amount -= Double.parseDouble(item.getHezje());
            }
        }
        return Result.ok(amount);
    }
}
